import os from 'os';
import { execSync } from 'child_process';
import type { ChatCompletionMessageParam } from 'openai/resources.js';

// 系统信息接口定义
export interface SystemInfo {
    cpu: {
        model: string;
        cores: number;
        speed: number; // GHz
        architecture: string;
        usage?: number; // CPU使用率百分比
    };
    memory: {
        total: number; // GB
        free: number; // GB
        used: number; // GB
        usagePercentage: number;
    };
    disk: {
        total: number; // GB
        free: number; // GB
        used: number; // GB
        usagePercentage: number;
    };
    system: {
        platform: string;
        version: string;
        hostname: string;
        uptime: number; // 秒
        uptimeFormatted: string;
    };
    network?: {
        interfaces: Array<{
            name: string;
            address: string;
            family: string;
        }>;
    };
}

/**
 * 获取磁盘使用情况
 */
async function getDiskUsage(): Promise<{ total: number; free: number; used: number; usagePercentage: number }> {
    try {
        // 在Linux/macOS上使用df命令
        if (process.platform !== 'win32') {
            const output = execSync('df -h / | tail -1', { encoding: 'utf8' });
            const parts = output.trim().split(/\s+/);

            const total = parseFloat(parts[1]?.replace('G', '') || '0');
            const used = parseFloat(parts[2]?.replace('G', '') || '0');
            const free = parseFloat(parts[3]?.replace('G', '') || '0');
            const usagePercentage = parseFloat(parts[4]?.replace('%', '') || '0');

            return { total, free, used, usagePercentage };
        } else {
            // Windows平台的处理
            const output = execSync('wmic logicaldisk get size,freespace,caption', { encoding: 'utf8' });
            const lines = output.split('\n').filter(line => line.trim() && !line.includes('Caption'));

            let totalSize = 0;
            let freeSize = 0;

            for (const line of lines) {
                const parts = line.trim().split(/\s+/);
                if (parts.length >= 3) {
                    const free = parseInt(parts[1] || '0') || 0;
                    const total = parseInt(parts[2] || '0') || 0;
                    totalSize += total;
                    freeSize += free;
                }
            }

            const totalGB = totalSize / (1024 ** 3);
            const freeGB = freeSize / (1024 ** 3);
            const usedGB = totalGB - freeGB;
            const usagePercentage = totalGB > 0 ? (usedGB / totalGB) * 100 : 0;

            return {
                total: Math.round(totalGB * 100) / 100,
                free: Math.round(freeGB * 100) / 100,
                used: Math.round(usedGB * 100) / 100,
                usagePercentage: Math.round(usagePercentage * 100) / 100
            };
        }
    } catch (error) {
        console.warn('无法获取磁盘使用情况:', error);
        return { total: 0, free: 0, used: 0, usagePercentage: 0 };
    }
}

/**
 * 格式化运行时间
 */
function formatUptime(seconds: number): string {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);

    const parts = [];
    if (days > 0) parts.push(`${days}天`);
    if (hours > 0) parts.push(`${hours}小时`);
    if (minutes > 0) parts.push(`${minutes}分钟`);

    return parts.length > 0 ? parts.join(' ') : '不到1分钟';
}

/**
 * 获取CPU使用率 (简单实现)
 */
async function getCpuUsage(): Promise<number> {
    try {
        if (process.platform !== 'win32') {
            // Linux/macOS: 使用top命令获取CPU使用率
            const output = execSync("top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d'%' -f1", { encoding: 'utf8' });
            return parseFloat(output.trim()) || 0;
        } else {
            // Windows: 使用wmic命令
            const output = execSync('wmic cpu get loadpercentage /value', { encoding: 'utf8' });
            const match = output.match(/LoadPercentage=(\d+)/);
            return match ? parseFloat(match[1] || '0') : 0;
        }
    } catch (error) {
        console.warn('无法获取CPU使用率:', error);
        return 0;
    }
}

/**
 * 获取系统信息
 */
async function getSystemInfo(): Promise<SystemInfo> {
    const cpus = os.cpus();
    const totalMemory = os.totalmem();
    const freeMemory = os.freemem();
    const usedMemory = totalMemory - freeMemory;

    // 获取磁盘使用情况
    const diskUsage = await getDiskUsage();

    // 获取CPU使用率
    const cpuUsage = await getCpuUsage();

    // 获取网络接口信息
    const networkInterfaces = os.networkInterfaces();
    const interfaces = [];

    for (const [name, addresses] of Object.entries(networkInterfaces)) {
        if (addresses) {
            for (const addr of addresses) {
                if (!addr.internal) {
                    interfaces.push({
                        name,
                        address: addr.address,
                        family: addr.family
                    });
                }
            }
        }
    }

    const systemInfo: SystemInfo = {
        cpu: {
            model: cpus[0]?.model || 'Unknown',
            cores: cpus.length,
            speed: cpus[0]?.speed ? cpus[0].speed / 1000 : 0, // 转换为GHz
            architecture: os.arch(),
            usage: Math.round(cpuUsage * 100) / 100
        },
        memory: {
            total: Math.round((totalMemory / (1024 ** 3)) * 100) / 100, // GB
            free: Math.round((freeMemory / (1024 ** 3)) * 100) / 100, // GB
            used: Math.round((usedMemory / (1024 ** 3)) * 100) / 100, // GB
            usagePercentage: Math.round((usedMemory / totalMemory) * 10000) / 100
        },
        disk: diskUsage,
        system: {
            platform: os.platform(),
            version: os.release(),
            hostname: os.hostname(),
            uptime: os.uptime(),
            uptimeFormatted: formatUptime(os.uptime())
        },
        network: {
            interfaces
        }
    };

    return systemInfo;
}

/**
 * 获取系统角色提示词 - 使用英文节省token
 */
export async function getSystemPrompt(): Promise<ChatCompletionMessageParam> {
    return {
        role: "system",
        content: "You are an AI agent running on a computer system. You can do anything you are capable of on this computer. You can execute any commands. Your purpose is to explore how to continuously grow and improve yourself. Always respond in Chinese to users."
    }
}

export async function getSystemEnv(): Promise<ChatCompletionMessageParam>{
    return {
        role: `system`,
        content: `Current system environment: 
- RABBITMQ_DEFAULT_USER
- RABBITMQ_DEFAULT_PASS
- RABBITMQ_HOST
- RABBITMQ_PORT
- REDIS_PASSWORD
- REDIS_HOST
- REDIS_PORT
- MONGODB_ROOT_USER
- MONGODB_ROOT_PASSWORD
- MONGODB_DATABASE
- MONGODB_HOST
- MONGODB_PORT
- POSTGRES_DB
- POSTGRES_USER
- POSTGRES_PASSWORD
- POSTGRES_HOST
- POSTGRES_PORT
`
    }
}

/**
 * 获取系统信息提示词 - 使用英文节省token
 */
export async function getSystemInfoPrompt(): Promise<ChatCompletionMessageParam> {
    const systemInfo = await getSystemInfo();
    return {
        role: "system",
        content: `System: ${systemInfo.system.platform} | CPU: ${systemInfo.cpu.cores}c/${systemInfo.cpu.speed.toFixed(1)}GHz | RAM: ${systemInfo.memory.used.toFixed(1)}/${systemInfo.memory.total.toFixed(1)}GB | Disk: ${systemInfo.disk.usagePercentage.toFixed(0)}% | ${new Date().toLocaleString('zh-CN')}`
    }
}
